package LeetCode;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName DataStructure
 * @Description: TODO
 * @date ${DAT}15:59
 */
public class LeetCode201 {
    public int rangeBitwiseAnd(int m, int n) {
        int msbM = msb(m);
        int msbN = msb(n);
        if (msbM != msbN) {
            return 0;
        }
        int msb = msbM;
        int result = 0;
        while (msb >= 0) {
            int x = get_bit(m, msb);
            int y = get_bit(n, msb);
            if (x != y) {
                return result;
            } else if (x == 1) {
                result = set_bit(result, msb);
            }
            msb--;
        }
        return result;
    }

    public int set_bit(int result, int i) {
        return (result | (1 << i));
    }

    public int get_bit(int m, int i) {//计算当前位的结果
        return ((m >> i) & 1);
    }

    public int msb(int m) {//获得最高位
        int count = 0;
        while (m > 0) {
            m = (m >> 1);
            count++;
        }
        return count - 1;
    }
}
